package com.itheima.health.controller;

import com.itheima.interfaces.OrderService;
import com.itheima.pojo.Order;
import com.itheima.resources.MessageConstant;
import com.itheima.resources.RedisMessageConstant;
import com.itheima.resources.entity.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RequestMapping("order")
@RestController
public class OrderController {
    @Reference
    private OrderService orderService;

    //注入redis工具类
    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("add.do")
    public Result add(@RequestBody Map map) {
        //  第一步：  判断验证码 是否有效
        String code = (String) map.get("validateCode");
        if (StringUtils.isNoneBlank(code)) {
            String telephone = (String) map.get("telephone");
            //  获取redis  指定的预约验证码
            String key = RedisMessageConstant.SENDTYPE_ORDER + telephone;
            String redisCode = (String) redisTemplate.opsForValue().get(key);
            //判断是否为空
            if (StringUtils.isBlank(redisCode)) {
                //验证码过期
                return new Result(false, MessageConstant.SEND_VALIDATECODE_TIMEOUT);
            } else if (!code.equals(redisCode)) {
                //验证码错误
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            } else {
                //  第二步： 验证码正确  预约业务  业务层完成
                Order order = orderService.add(map);
                //  发送短信给客户 短信通知     通知客户 预约成功。。。。
                return new Result(true, MessageConstant.ADD_ORDER_SUCCESS, order);
            }

        } else {
            return new Result(false, "数据非法");
        }


    }

    @RequestMapping("findOrderInfoByOrderId.do")
    public Result findSetMealDetail(@RequestParam("orderid") Integer orderid) {

        try {
            Map map = orderService.findSetMealDetail(orderid);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
